const ADD = 'ADD';

const initState = {
  name: '天启',
  count: 0,
};

// redux原理
const reducer = (state = initState, action) => {
  switch (action.type) {
    case ADD:
      return {
        ...state,
        count: state.count + 1,
      };
    default:
      return state;
  }
};

//
const store = myCreateStore(reducer, initState, enhancer); // reducer function initState

function myCreateStore(reducer, preloadedState, enhancer) {
  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('enhancer必须是函数');
    }
    return enhancer(myCreateStore)(reducer, preloadedState);
  }
  let currentState = preloadedState;

  // 监听的数组列表
  const currentListeners = [];
  function dispatch(action) {
    currentState = reducer(currentState, action);
    currentListeners.forEach(cb => cb());
  }
  function subscribe(fn) {
    currentListeners.push(fn);
  }
  function getState() {
    return currentState;
  }

  dispatch({
    type: 'initAction',
  });

  return {
    getState,
    subscribe,
    dispatch,
  };
}

function enhancer(createStore) {
  return function (reducer, preloadedState) {
    const store = createStore(reducer, preloadedState);
    const dispatch = store.dispatch; // {type: 'ADD'}
    function _dispatch(action) {
      if (typeof action === 'function') {
        return action(dispatch);
      }
      dispatch(action);
    }

    return {
      ...store,
      dispatch: _dispatch,
    };
  };
}

store.dispatch({ type: 'ADD' });
console.log(store.getState());

store.dispatch(function (dispatch) {
  setTimeout(() => {
    dispatch({
      type: ADD,
    });

    console.log(store.getState());
  }, 1000);
});

export default store;
